package com.android.delivery.activity.wangdian

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.ada.common.util.CollectionUtil
import com.android.delivery.R
import com.android.delivery.adapter.siji.OrderAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseActivity
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.constant.IntentKeyConstant
import com.android.delivery.entity.Arrived
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.even.RefreshConfirmJieChe
import com.android.delivery.util.ToastUtils
import com.blankj.utilcode.util.ObjectUtils
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.android.synthetic.main.activity_dai_jie_che_detail.*
import kotlinx.android.synthetic.main.include_no_data.*
import org.greenrobot.eventbus.EventBus

/**
 * @author: mqwang
 * @create: 3/20/21 10:39 AM
 * @Description: 待接车详情
 */
class DaiJieCheDetailsActivity : BaseActivity(), OnRefreshLoadMoreListener {

    companion object {
        fun self(context: Activity, item: Arrived, requestCode: Int) {
            val intent = Intent(context, DaiJieCheDetailsActivity::class.java)
            intent.putExtra(Constants.ITEM, item)
            context.startActivityForResult(intent, requestCode)
        }
    }

    private var driver: Arrived? = null
    private var page = 1

    private val orderAdapter: OrderAdapter by lazy {
        OrderAdapter()
    }

    fun bindRecyclerView(recLv: RecyclerView?) {
        driver = intent.getParcelableExtra<Arrived>(Constants.ITEM)
        orderAdapter.setType(0)
        recLv!!.adapter = orderAdapter
        orderAdapter.setOnItemClickListener { adapter, view, position ->
            orderAdapter.selectItem(position)
        }
    }

    fun loadData(page: Int, pageCount: Int) {
        ApiService.order_arrived_items(this, driver!!.userId, page, object : DialogCallback<LzyResponse<Logistics>>() {
            override fun onSuccess(response: Response<LzyResponse<Logistics>>?) {
                onGetDataSuc(response!!.body().data.records)
            }
        })
    }

    fun getData(): MutableList<Logistics> {
        return orderAdapter.data
    }

    fun bindData(isRefresh: Boolean, list: List<Logistics>?) {
        if (isRefresh) orderAdapter.setNewData(list) else orderAdapter.addData(list!!)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_dai_jie_che_detail
    }

    override fun init(savedInstanceState: Bundle?, container: View?) {
        setMainTitle("待接车明细")
        bindRecyclerView(recyclerView)
        refreshLayout.setOnRefreshListener(this)
        refreshLayout.setOnLoadMoreListener(this)

        tv_select_all.setOnClickListener {
            tv_select_all.isSelected = !tv_select_all.isSelected
            orderAdapter.selectAllItem(tv_select_all.isSelected)
        }

        tv_send.setOnClickListener {
            val selectIdList = orderAdapter.getSelectIdList()
            if (ObjectUtils.isEmpty(selectIdList)) {
                ToastUtils.showShort(this, "至少选中一条")
                return@setOnClickListener
            }
            ApiService.transport_Sign(this, selectIdList, object : DialogCallback<LzyResponse<Any>>(this) {
                override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                    ToastUtils.showShort(this@DaiJieCheDetailsActivity, "操作成功")
                    EventBus.getDefault().post(RefreshConfirmJieChe())
                    onRefresh(refreshLayout)
                }
            })
        }

        if (driver != null) {
            tv_name.setText(driver?.realName)
            tv_phone.setText(driver?.mobile)
            tv_num.setText(String.format("%d件", driver?.quantity))
        }

        refreshLayout.autoRefresh()
    }

    override fun onLoadMore(refreshlayout: RefreshLayout) {
        loadData(page, IntentKeyConstant.PAGE_COUNT)
    }

    override fun onRefresh(refreshlayout: RefreshLayout) {
        page = 1
        loadData(page, IntentKeyConstant.PAGE_COUNT)
    }

    /**
     * 拉取数据成功时调用
     * @param data 数据源
     */
    protected fun onGetDataSuc(data: List<Logistics>) {
        finishRefresh(refreshLayout)
        bindData(isRefresh(), data)
        tv_num.setText(String.format("%d件", if (data == null) 0 else data.size))
        if (!ObjectUtils.isEmpty(data)) {
            page++
        }
        //        else{//判断是否显示无数据界面
//            checkData();
//
//        }
        checkData()
        if (CollectionUtil.getSize(data) < IntentKeyConstant.PAGE_COUNT) { //无更多
            refreshLayout.setNoMoreData(true) //将不会再次触发加载更多事件
        } else {
            refreshLayout.setNoMoreData(false) //还有更多
        }
    }

    private fun checkData() {
        if (!ObjectUtils.isEmpty(getData())) {
            layout_empty.setVisibility(View.GONE)
        } else {
            layout_empty.setVisibility(View.VISIBLE)
        }
    }

    private fun isRefresh(): Boolean {
        return page == 1
    }
}